<template>
  <div class="container">
    <div class="container_title">
      {{ ruleForm.entityName }}
      <div class="container_title_type">
        <el-button :disabled="true" plain @click="null">
          <template #default>
            <div class="container_title_type_icon">
              <div class="container_title_type_icon_con"></div>
            </div>
            {{ identityEnum[identity] }}
          </template>
        </el-button>
        <el-button :disabled="true" plain>
          <template #default>
            <div class="container_title_type_icon">
              <div class="container_title_type_icon_con"></div>
            </div>
            {{ nationalityEnum[nationality] }}
          </template>
        </el-button>
        <el-icon class="close" @click="iconClosePage"><CloseBold /></el-icon>
      </div>
    </div>
    <el-tabs v-model="activeTab" class="demo-tabs">
      <el-tab-pane class="abstract" :label="$t('entity.manage_tab_abstract')" name="first">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          inline
          label-position="top"
          require-asterisk-position="right"
        >
          <!-- 实体一般信息 -->
          <div v-if="nowType" class="general">
            <h5 class="general_title">
              {{ $t('entity.add_general') }}
            </h5>
            <div class="general_content">
              <!-- 实体类型 -->
              <el-form-item :label="$t('entity.add_general_entityType')" prop="entityType" class="common">
                <el-select
                  v-model="ruleForm.entityType"
                  :placeholder="$t('entity.add_general_entityType')"
                  :disabled="onlyRead"
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="item in entityTypeOptions"
                    :key="item.value"
                    :label="$t(item.label)"
                    :value="item.value"
                    :disabled="item.disabled"
                  />
                </el-select>
              </el-form-item>
              <!-- 实体名称 -->
              <el-form-item :label="$t('entity.add_general_entityName')" prop="entityName" class="common">
                <el-input v-model="ruleForm.entityName" :disabled="onlyRead" autosize type="textarea" resize="none" />
              </el-form-item>
              <!-- 文件 -->
              <el-form-item :label="$t('entity.add_general_document')" prop="document" class="common document">
                <el-select
                  v-model="ruleForm.documentType"
                  :placeholder="$t('entity.add_general_documentType')"
                  :style="{ width: '160px', marginRight: '10px' }"
                  :disabled="onlyRead"
                >
                  <el-option
                    v-for="item in documentTypeOptions"
                    :key="item.value"
                    :label="$t(item.label)"
                    :value="item.value"
                    :disabled="item.disabled"
                  />
                </el-select>
                <el-input
                  v-model="ruleForm.documentNumber"
                  class="input-with-select"
                  :disabled="onlyRead"
                  autosize
                  type="textarea"
                  resize="none"
                />
              </el-form-item>
              <!-- 交易名称 -->
              <el-form-item
                v-if="nowType === 'LB' || nowType === 'LF'"
                :label="$t('entity.add_general_socialReason')"
                prop="tradeName"
              >
                <el-input v-model="ruleForm.tradeName" :disabled="onlyRead" autosize type="textarea" resize="none" />
              </el-form-item>
              <!-- 州登记 -->
              <el-form-item
                v-if="nowType === 'LB' || nowType === 'LF'"
                :label="$t('entity.add_general_stateRegistration')"
                prop="stateRegistration"
              >
                <el-input
                  v-model="ruleForm.stateRegistration"
                  :disabled="onlyRead"
                  autosize
                  type="textarea"
                  resize="none"
                />
              </el-form-item>
              <!-- 城市登记 -->
              <el-form-item
                v-if="nowType === 'LB' || nowType === 'LF'"
                :label="$t('entity.add_general_municipalRegistration')"
                prop="cityRegistration"
              >
                <el-input
                  v-model="ruleForm.cityRegistration"
                  :disabled="onlyRead"
                  autosize
                  type="textarea"
                  resize="none"
                />
              </el-form-item>
              <!-- 职业 -->
              <el-form-item
                v-if="nowType === 'PB' || nowType === 'PF'"
                :label="$t('entity.add_general_profession')"
                prop="profession"
              >
                <el-input v-model="ruleForm.profession" :disabled="onlyRead" autosize type="textarea" resize="none" />
              </el-form-item>
              <!-- OAB -->
              <el-form-item
                v-if="nowType === 'PB' && isLawyer"
                :label="$t('entity.add_general_oab')"
                prop="attorneyRegistrationNumber"
              >
                <el-input
                  v-model="ruleForm.attorneyRegistrationNumber"
                  :disabled="onlyRead || !isLawyer"
                  autosize
                  type="textarea"
                  resize="none"
                />
              </el-form-item>
              <!-- RG -->
              <el-form-item v-if="nowType === 'PB'" :label="$t('entity.add_general_rg')" prop="idCard">
                <el-input v-model="ruleForm.idCard" :disabled="onlyRead" autosize type="textarea" resize="none" />
              </el-form-item>
              <!-- 婚姻状况 -->
              <el-form-item
                v-if="nowType === 'PB' || nowType === 'PF'"
                :label="$t('entity.add_general_civilStatus')"
                prop="marriageStatus"
              >
                <el-select
                  v-model="ruleForm.marriageStatus"
                  :placeholder="$t('entity.add_general_civilStatus')"
                  :disabled="onlyRead"
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="item in civilStatusOptions"
                    :key="item.value"
                    :label="$t(item.label)"
                    :value="item.value"
                    :disabled="item.disabled"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>

          <!-- 实体地址信息 -->
          <div v-if="nowType" class="address">
            <h5 class="address_title">
              {{ $t('entity.add_address') }}
            </h5>
            <div class="address_content">
              <!-- 邮编 -->
              <el-form-item :label="$t('entity.add_address_cep')" prop="zipCode" class="common">
                <el-input v-model="ruleForm.zipCode" :disabled="onlyRead" autosize type="textarea" resize="none" />
              </el-form-item>
              <!-- 街号 -->
              <el-form-item :label="$t('entity.add_address_number')" prop="streetNumber" class="common">
                <el-input v-model="ruleForm.streetNumber" :disabled="onlyRead" autosize type="textarea" resize="none" />
              </el-form-item>
              <!-- 地址 -->
              <el-form-item :label="$t('entity.add_address_address')" prop="address" class="common">
                <el-input
                  v-model="ruleForm.address"
                  :disabled="ruleForm.isBaxiCep || onlyRead"
                  autosize
                  type="textarea"
                  resize="none"
                />
              </el-form-item>
              <!-- 地区 -->
              <el-form-item :label="$t('entity.add_address_district')" prop="district" class="common">
                <el-input
                  v-model="ruleForm.district"
                  :disabled="ruleForm.isBaxiCep || onlyRead"
                  autosize
                  type="textarea"
                  resize="none"
                />
              </el-form-item>
              <!-- 国家省市 -->
              <el-form-item
                :label="
                  $t('entity.add_address_country') +
                  '/' +
                  $t('entity.add_address_state') +
                  '/' +
                  $t('entity.add_address_city')
                "
                prop="countryStateCity"
                class="common csc"
              >
                <el-select
                  v-model="ruleForm.country"
                  filterable
                  :placeholder="$t('entity.add_address_country')"
                  :disabled="ruleForm.isBaxiCep || onlyRead"
                >
                  <el-option v-for="item in countryOptions" :key="item.id" :label="item.name" :value="item.name" />
                </el-select>
                <el-select
                  v-model="ruleForm.state"
                  filterable
                  :placeholder="$t('entity.add_address_state')"
                  :disabled="!ruleForm.country || ruleForm.isBaxiCep || onlyRead"
                >
                  <el-option v-for="item in stateOptions" :key="item.id" :label="item.name" :value="item.name" />
                </el-select>
                <el-select
                  v-model="ruleForm.city"
                  filterable
                  :placeholder="$t('entity.add_address_city')"
                  :disabled="!ruleForm.state || ruleForm.isBaxiCep || onlyRead"
                >
                  <el-option v-for="item in cityOptions" :key="item.id" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
            </div>
          </div>
          <!-- 实体联系信息 -->
          <div v-if="nowType" class="contact">
            <h5 class="contact_title">{{ $t('entity.add_contact') }}</h5>
            <div class="contact_content">
              <!-- 姓名 -->
              <el-form-item :label="$t('entity.add_contact_name')" prop="name">
                <el-input v-model="ruleForm.name" :disabled="onlyRead" autosize type="textarea" resize="none" />
              </el-form-item>
              <!-- 邮箱 -->
              <el-form-item :label="$t('entity.add_contact_email')" prop="email">
                <el-input v-model="ruleForm.email" :disabled="onlyRead" autosize type="textarea" resize="none" />
              </el-form-item>
              <!-- 手机号1 -->
              <el-form-item :label="$t('entity.add_contact_phoneNumber1')" prop="phoneNumber" class="phoneNumber1">
                <el-select
                  v-model="ruleForm.phoneAreaCode1"
                  :placeholder="$t('entity.add_contact_phoneNumber_areacode')"
                  :style="{ width: '160px', marginRight: '10px' }"
                  :disabled="onlyRead"
                >
                  <el-option
                    v-for="item in areaCodeOptions.value"
                    :key="item.id"
                    :label="item.phoneCode"
                    :value="item.phoneCode"
                  />
                </el-select>
                <el-input
                  v-model="ruleForm.phoneNumber1"
                  class="input-with-select"
                  :disabled="onlyRead"
                  autosize
                  type="textarea"
                  resize="none"
                />
              </el-form-item>
              <!-- 手机号2 -->
              <el-form-item :label="$t('entity.add_contact_phoneNumber2')" prop="phoneNumber2" class="phoneNumber2">
                <el-select
                  v-model="ruleForm.phoneAreaCode2"
                  :placeholder="$t('entity.add_contact_phoneNumber_areacode')"
                  :style="{ width: '160px', marginRight: '10px' }"
                  :disabled="onlyRead"
                >
                  <el-option
                    v-for="item in areaCodeOptions.value"
                    :key="item.id"
                    :label="item.phoneCode"
                    :value="item.phoneCode"
                  />
                </el-select>
                <el-input
                  v-model="ruleForm.phoneNumber2"
                  class="input-with-select"
                  :disabled="onlyRead"
                  autosize
                  type="textarea"
                  resize="none"
                />
              </el-form-item>
            </div>
          </div>
          <div v-if="!onlyRead" class="btn">
            <el-form-item>
              <el-button @click="resetForm(ruleFormRef)">{{ $t('entity.manage_btn_reset') }}</el-button>
              <el-button type="primary" @click="saveForm(ruleFormRef)">{{ $t('entity.manage_btn_confirm') }}</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-tab-pane>
      <el-tab-pane class="historicalData" :label="$t('entity.manage_tab_historicalData')" name="second">
        <el-form :model="formInline" style="margin-left: 0">
          <el-form-item>
            <el-date-picker
              v-model="formInline.date"
              type="datetimerange"
              :start-placeholder="$t('entity.list_query_createTime_start')"
              :end-placeholder="$t('entity.list_query_createTime_end')"
              format="DD-MM-YYYY HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item class="btn">
            <el-button type="primary" @click="getEntityModificationList(true)">{{
              $t('entity.manage_query_text')
            }}</el-button>
          </el-form-item>
        </el-form>
        <el-table
          :data="tableData"
          header-row-class-name="table_header"
          style="width: 100%"
          :header-cell-style="{
            backgroundColor: '#F6F8F7',
          }"
        >
          <el-table-column
            prop="fieldName"
            :label="$t('entity.manage_tab_historicalData_list_field')"
            min-width="18%"
          />
          <el-table-column
            prop="sourceValue"
            :label="$t('entity.manage_tab_historicalData_list_before')"
            min-width="23%"
          />
          <el-table-column
            prop="updateValue"
            :label="$t('entity.manage_tab_historicalData_list_after')"
            min-width="23%"
          />
          <el-table-column
            prop="updateUser"
            :label="$t('entity.manage_tab_historicalData_list_user')"
            min-width="18%"
          />

          <el-table-column
            prop="updateTime"
            :label="$t('entity.manage_tab_historicalData_list_modificationDate')"
            min-width="18%"
          />
        </el-table>
        <div v-if="pageCount" class="list_pagination">
          <el-pagination
            v-model:currentPage="tableParams.page"
            layout="prev, pager, next"
            :total="pageCount"
            @update:current-page="currentPageChange"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, computed, watch } from 'vue';
import entityApi from '@/apis/entity';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useStore } from 'vuex';
import type { FormInstance } from 'element-plus';
import { ElMessageBox, ElLoading, ElMessage } from 'element-plus';
import { getRequest } from '@/apis/request';
import router from '@/router';
import loadsh from 'lodash';
let { t } = useI18n();
const store = useStore();

const isLawyer = store.state.user.roles.includes('legal');

const uid = store.state.user.info.id;
const locale = store.state.locale.key;
const activeTag = store.state.menu.activeTag;
const tagList = store.state.menu.tagList;
const query: any = useRouter().currentRoute.value.query;
const ruleFormRef = ref<FormInstance>();
const formInline = reactive({
  date: ['', ''],
});
const identityEnum: any = computed(() => {
  return {
    legal: t('entity.manage_basic_identity_legal'),
    physics: t('entity.manage_basic_identity_physics'),
  };
});
const nationalityEnum: any = computed(() => {
  return {
    brazilian: t('entity.manage_basic_nationality_brazilian'),
    foreign: t('entity.manage_basic_nationality_foreign'),
  };
});
const identity = ref('');
const nationality = ref('');
const activeTab = ref('first');
const pageCount = ref(0);
const tableParams = reactive({
  page: 1,
  pageSize: 10,
});
const tableData = ref([]);
const isConfirm = ref(false);
let countryOptions: any = ref([]);
let stateOptions: any = ref([]);
let cityOptions: any = ref([]);
const entityTypeOptions = reactive([
  {
    value: 101,
    label: 'entity.add_general_entityType_supplier',
    disabled: false,
  },
  {
    value: 102,
    label: 'entity.add_general_entityType_franchised',
    disabled: false,
  },
  {
    value: 106,
    label: 'entity.add_general_entityType_granted',
    disabled: false,
  },
  {
    value: 104,
    label: 'entity.add_general_entityType_complainant',
    disabled: false,
  },
  {
    value: 105,
    label: 'entity.add_general_entityType_defendant',
    disabled: false,
  },
  {
    value: 107,
    label: 'entity.add_general_entityType_grantor',
    disabled: false,
  },
  {
    value: 103,
    label: 'entity.add_general_entityType_lawyer',
    disabled: false,
  },
  {
    value: 108,
    label: 'entity.add_general_entityType_groupCompany',
    disabled: !isLawyer,
  },
]);
const civilStatusOptions = reactive([
  {
    value: 201,
    label: 'entity.add_general_civilStatus_unique',
    disabled: false,
  },
  {
    value: 202,
    label: 'entity.add_general_civilStatus_married',
    disabled: false,
  },
  {
    value: 203,
    label: 'entity.add_general_civilStatus_widow',
    disabled: false,
  },
  {
    value: 204,
    label: 'entity.add_general_civilStatus_divorce',
    disabled: false,
  },
  {
    value: 205,
    label: 'entity.add_general_civilStatus_buried',
    disabled: false,
  },
  {
    value: 206,
    label: 'entity.add_general_civilStatus_other',
    disabled: false,
  },
]);
let areaCodeOptions = reactive({
  value: [
    {
      id: '86',
      phoneCode: '+86',
    },
  ],
});
const documentTypeOptions = computed(() => [
  {
    value: 301,
    label: 'entity.add_general_documentType_cnpj',
    disabled: !(nowType.value === 'LF' || nowType.value === 'LB'),
  },
  {
    value: 303,
    label: 'entity.add_general_documentType_cpf',
    disabled: !(nowType.value === 'PB'),
  },
  {
    value: 302,
    label: 'entity.add_general_documentType_nif',
    disabled: !(nowType.value === 'LF'),
  },
  {
    value: 304,
    label: 'entity.add_general_documentType_rne',
    disabled: !(nowType.value === 'PF'),
  },
  {
    value: 305,
    label: 'entity.add_general_documentType_rnm',
    disabled: !(nowType.value === 'PF'),
  },
]);
const ruleFormCopy: any = reactive({
  value: {
    identity: identity,
    nationality: nationality,
    entityType: '',
    entityName: '',
    documentNumber: '',
    documentType: '',
    idCard: '',
    attorneyRegistrationNumber: '',
    profession: '',
    marriageStatus: '',
    tradeName: '',
    stateRegistration: '',
    cityRegistration: '',
    isBaxiCep: false,
    zipCode: '',
    streetNumber: '',
    address: '',
    district: '',
    country: '',
    state: '',
    city: '',

    name: '',
    email: '',
    phoneNumber1: '',
    phoneNumber2: '',
    phoneAreaCode1: '',
    phoneAreaCode2: '',
  },
});
const temp: any = ref({});
const ruleForm = computed(() => {
  return ruleFormCopy.value;
});
watch(
  [
    () => ruleForm.value.country,
    () => ruleForm.value.state,
    () => ruleForm.value.zipCode,
    () => ruleForm.value.documentNumber,
  ],
  (newValue, oldValue) => {
    if (!oldValue[0] && !oldValue[1] && !oldValue[2] && !oldValue[3]) {
      return;
    } else if (newValue[0] !== oldValue[0] && newValue[0] !== '' && !ruleForm.value.isBaxiCep) {
      ruleForm.value.state = '';
      ruleForm.value.city = '';
      const country = countryOptions.value.find((item: any) => ruleForm.value.country === item.name);
      entityApi.getStateList({ locale, countryId: country.id }).then((res: { code: number; data: any }) => {
        if (!!res && res.code === 200) {
          stateOptions.value = res.data;
        }
      });
    } else if (newValue[1] !== oldValue[1] && newValue[1] !== '' && !ruleForm.value.isBaxiCep) {
      ruleForm.value.city = '';
      const state = stateOptions.value.find((item: any) => item.name.includes(ruleForm.value.state));
      entityApi.getCityList({ locale, statesId: state.id }).then((res: { code: number; data: any }) => {
        if (!!res && res.code === 200) {
          if (res.data.length) {
            cityOptions.value = res.data;
          } else {
            cityOptions.value = [
              {
                name: state.name,
                id: state.id,
              },
            ];
          }
        }
      });
    } else if (
      newValue[2] !== oldValue[2] &&
      (nowType.value === 'LB' || nowType.value === 'PB') &&
      newValue[2].length === 8 &&
      /^[0-9]{8}$/.test(newValue[2])
    ) {
      getViaCep(newValue[2]);
    } else if (
      newValue[2] !== oldValue[2] &&
      (nowType.value === 'LB' || nowType.value === 'PB') &&
      newValue[2].length !== 8 &&
      ruleForm.value.isBaxiCep
    ) {
      ruleForm.value.isBaxiCep = false;
      ruleForm.value.address = '';
      ruleForm.value.district = '';
      ruleForm.value.streetNumber = '';
      ruleForm.value.country = '';
      ruleForm.value.state = '';
      ruleForm.value.city = '';
    }
  },
  { deep: true, immediate: true },
);
const onlyRead = computed(() => {
  return (!isLawyer && ruleForm.value.entityType === 108) || (!isLawyer && !!ruleForm.value.attorneyRegistrationNumber);
});
const nowType = computed(() => {
  let res: any = null;
  if (identity.value === 'legal') {
    if (nationality.value === 'brazilian') {
      res = 'LB';
    } else if (nationality.value === 'foreign') {
      res = 'LF';
    }
  } else if (identity.value === 'physics') {
    if (nationality.value === 'brazilian') {
      res = 'PB';
    } else if (nationality.value === 'foreign') {
      res = 'PF';
    }
  }
  return res;
});
let tipsMandatory = computed(() => t('entity.add_tips_mandatory'));
let tipsFormat = computed(() => t('entity.add_tips_format'));
let tipsUniqueness = computed(() => t('entity.add_tips_uniqueness'));
const rules = computed(() => {
  return {
    // general
    entityType: [{ required: false, validator: validate, trigger: ['blur', 'change'] }],
    entityName: [{ required: false, validator: validate, trigger: ['blur', 'change'] }],
    document: [{ required: false, validator: validateDocument, trigger: ['blur', 'change'] }],
    // address
    zipCode: [{ required: false, validator: validateCep, trigger: ['blur', 'change'] }],
    streetNumber: [{ required: false, validator: validate, trigger: ['blur', 'change'] }],
    address: [{ required: false, validator: validate, trigger: ['blur', 'change'] }],
    district: [{ required: false, validator: validate, trigger: ['blur', 'change'] }],
    countryStateCity: [{ required: false, validator: validateCountryStateCity, trigger: ['blur', 'change'] }],
    // concat
    email: [{ required: false, validator: validateEmail, type: 'email', trigger: ['blur', 'change'] }],
    tipsMandatory: t('entity.add_tips_mandatory'),
    tipsFormat: t('entity.add_tips_format'),
    tipsUniqueness: t('entity.add_tips_uniqueness'),
  };
});
const validate = (rule: any, value: any, callback: any) => {
  if (!value && isConfirm.value) {
    callback(new Error(tipsMandatory.value));
  } else {
    callback();
  }
};
const validateEmail = (rule: any, value: any, callback: any) => {
  if (!value && isConfirm.value) {
    callback();
  } else if (!/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(value) && isConfirm.value) {
    callback(new Error(tipsFormat.value));
  } else {
    callback();
  }
};
const validateCep = (rule: any, value: any, callback: any) => {
  if (!value && isConfirm.value) {
    callback(new Error(tipsMandatory.value));
  } else if (
    !/^[0-9]{8}$/.test(value) &&
    value &&
    (nowType.value === 'PB' || nowType.value === 'LB') &&
    isConfirm.value
  ) {
    callback(new Error(tipsFormat.value));
  } else {
    callback();
  }
};
const validateDocument = (rule: any, value: any, callback: any) => {
  if ((!ruleForm.value.documentType || !ruleForm.value.documentNumber) && isConfirm.value) {
    callback(new Error(tipsMandatory.value));
  } else if (ruleForm.value.documentType === 301 && ruleForm.value.documentNumber && isConfirm.value) {
    entityApi.verifyCNPJ({ cnpj: ruleForm.value.documentNumber }).then((res: { data: any }) => {
      if (res.data) {
        entityApi
          .verifyUniqueness({ docNum: ruleForm.value.documentNumber, id: query.id })
          .then((res: { data: any }) => {
            if (res.data) {
              callback();
            } else {
              callback(new Error(tipsUniqueness.value));
            }
          });
      } else {
        callback(new Error(tipsFormat.value));
      }
    });
  } else if (ruleForm.value.documentType === 303 && ruleForm.value.documentNumber && isConfirm.value) {
    entityApi.verifyCPF({ cpf: ruleForm.value.documentNumber }).then((res: { data: any }) => {
      if (res.data) {
        entityApi
          .verifyUniqueness({ docNum: ruleForm.value.documentNumber, id: query.id })
          .then((res: { data: any }) => {
            if (res.data) {
              callback();
            } else {
              callback(new Error(tipsUniqueness.value));
            }
          });
      } else {
        callback(new Error(tipsFormat.value));
      }
    });
  } else if (ruleForm.value.documentType && ruleForm.value.documentNumber && isConfirm.value) {
    entityApi.verifyUniqueness({ docNum: ruleForm.value.documentNumber, id: query.id }).then((res: { data: any }) => {
      if (res.data) {
        callback();
      } else {
        callback(new Error(tipsUniqueness.value));
      }
    });
  } else {
    callback();
  }
};
const validateCountryStateCity = (rule: any, value: any, callback: any) => {
  if ((!ruleForm.value.country || !ruleForm.value.state || !ruleForm.value.city) && isConfirm.value) {
    callback(new Error(tipsMandatory.value));
  } else {
    callback();
  }
};
const currentPageChange = () => {
  getEntityModificationList();
};
const getEntityModificationList = (isQuery?: any) => {
  if (isQuery) {
    tableParams.page = 1;
  }
  entityApi
    .getEntityModificationList(
      Object.assign(
        {},
        {
          entityId: parseInt(query.id),
          startTime:
            (formInline.date &&
              formInline.date[0] &&
              (formInline.date[0] as any).toLocaleString().replace(/[/]/g, '-')) ||
            '',
          endTime:
            (formInline.date &&
              formInline.date[1] &&
              (formInline.date[1] as any).toLocaleString().replace(/[/]/g, '-')) ||
            '',
        },
        tableParams,
      ),
    )
    .then((res) => {
      if (!!res && res.code === 200 && res.data) {
        tableData.value = res.data.records;
        pageCount.value = res.data.total;
      } else {
        tableData.value = [];
        pageCount.value = 0;
      }
    });
};
const saveForm = loadsh.debounce(async (formEl: FormInstance | undefined) => {
  isConfirm.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    isConfirm.value = false;
    if (valid) {
      console.log('submit!');
      entityApi.confirmeEntity({ ...ruleForm.value, uid }).then((res) => {
        if (res.data) {
          router.push('/entityList');
          closePage();
          ElMessage({
            message: res.msg,
            type: 'success',
          });
        }
        if (res.code === 5020) {
          router.push('/entityList');
          closePage();
        }
      });
    } else {
      ElMessageBox.alert(t('entity.add_tips_confirm_fail'), {
        type: 'warning',
      });
      console.log('error submit!', fields);
    }
  });
}, 500);

const resetForm = loadsh.debounce((formEl: FormInstance | undefined) => {
  ruleForm.value.phoneAreaCode1 = temp.value.phoneAreaCode1;
  ruleForm.value.phoneAreaCode2 = temp.value.phoneAreaCode2;
  ruleForm.value.phoneNumber1 = temp.value.phoneNumber1;
  ruleForm.value.phoneNumber2 = temp.value.phoneNumber2;
  ruleForm.value.country = temp.value.country;
  ruleForm.value.isBaxiCep = temp.value.isBaxiCep;
  const country = countryOptions.value.find((item: any) => item.name.includes(ruleForm.value.country));
  !temp.value.isBaxiCep &&
    entityApi.getStateList({ locale, countryId: country.id }).then((res) => {
      if (!!res && res.data && res.code === 200) {
        stateOptions.value = res.data;
        ruleForm.value.state = temp.value.state;
        const state = stateOptions.value.find((item: any) => item.name.includes(ruleForm.value.state));
        entityApi.getCityList({ locale, statesId: state.id }).then((res) => {
          if (!!res && res.data && res.code === 200) {
            if (res.data.length) {
              cityOptions.value = res.data;
            } else {
              cityOptions.value = [
                {
                  name: state.name,
                  id: state.id,
                },
              ];
            }
            ruleForm.value.city = temp.value.city;
          }
        });
      }
    });

  ruleForm.value.documentType = temp.value.documentType;
  ruleForm.value.documentNumber = temp.value.documentNumber;
  if (!formEl) return;
  formEl.resetFields();
}, 500);
const getViaCep = (zipCode: String) => {
  getRequest('https://viacep.com.br/ws/' + zipCode + '/json/', {}).then((res) => {
    if (!res.erro) {
      ruleForm.value.address = res.logradouro;
      ruleForm.value.district = res.bairro;
      ruleForm.value.streetNumber = res.complemento;
      ruleForm.value.country = 'Brasil';
      ruleForm.value.state = res.uf;
      ruleForm.value.city = res.localidade;
      ruleForm.value.isBaxiCep = true;
    } else {
      ruleForm.value.isBaxiCep = false;
    }
    getCSC();
    temp.value = Object.assign({}, ruleFormCopy.value);
  });
};
const init = () => {
  if (query.id) {
    const loading = ElLoading.service({
      lock: true,
      text: 'loading',
    });
    entityApi.getEntityById({ id: query.id }).then((res: any) => {
      if (!!res && res.code === 200 && res.data) {
        identity.value = res.data.entityItem.identity === 1 ? 'legal' : 'physics';
        nationality.value = res.data.entityItem.nationality === 1 ? 'brazilian' : 'foreign';
        if (identity.value === 'legal') {
          if (nationality.value === 'brazilian') {
            ruleFormCopy.value = res.data.entityItem;
            if (res.data.entityItem.zipCode.length === 8) {
              getViaCep(res.data.entityItem.zipCode);
            }
          } else if (nationality.value === 'foreign') {
            ruleFormCopy.value = res.data.entityItem;
            getCSC();
            temp.value = Object.assign({}, ruleFormCopy.value);
          }
        } else if (identity.value === 'physics') {
          if (nationality.value === 'brazilian') {
            ruleFormCopy.value = res.data.entityItem;
            if (res.data.entityItem.zipCode.length === 8) {
              getViaCep(res.data.entityItem.zipCode);
            }
          } else if (nationality.value === 'foreign') {
            ruleFormCopy.value = res.data.entityItem;
            getCSC();
            temp.value = Object.assign({}, ruleFormCopy.value);
          }
        }
      }

      loading.close();
    });

    getEntityModificationList();
  }
  entityApi.getAreaCodeList({ locale }).then((res) => {
    if (!!res && res.data && res.code === 200) {
      areaCodeOptions.value = res.data;
    }
  });
};
init();
const getCSC = () => {
  entityApi.getCountryList({ locale }).then((res) => {
    if (!!res && res.data && res.code === 200) {
      countryOptions.value = res.data;
      const country = countryOptions.value.find((item: any) => item.name.includes(ruleForm.value.country));
      if (!ruleForm.value.isBaxiCep) {
        entityApi.getStateList({ locale, countryId: country.id }).then((res) => {
          if (!!res && res.data && res.code === 200) {
            stateOptions.value = res.data;
            const state = stateOptions.value.find((item: any) => item.name.includes(ruleForm.value.state));
            entityApi.getCityList({ locale, statesId: state.id }).then((res) => {
              if (!!res && res.data && res.code === 200) {
                if (res.data.length) {
                  cityOptions.value = res.data;
                } else {
                  cityOptions.value = [
                    {
                      name: state.name,
                      id: state.id,
                    },
                  ];
                }
              }
            });
          }
        });
      }
    }
  });
};
const closePage = () => {
  const newTagList = tagList.filter((a: any) => a.name !== activeTag);
  store.commit('setTagList', newTagList);
  store.commit('removeCacheRoute', [activeTag]);
};
const iconClosePage = () => {
  router.go(-1);
};
</script>

<style lang="scss" scoped>
h3,
h5 {
  font-size: 18px;
}
.container {
  background-color: white;
  border-radius: 10px;
  padding: 20px 24px;
  position: relative;
  &_title {
    display: flex;
    font-size: 18px;
    font-weight: bold;
    line-height: 32px;
    padding-bottom: 20px;
    box-shadow: inset 0 -1px 0 0 #edf1ef;
    justify-content: space-between;
    &_type {
      margin-left: 30px;
      display: flex;
      align-items: center;
      .close {
        margin-left: 10px;
      }
      .el-button {
        background-color: #f5faf7;
        border: 1px solid #419b62;
        border-radius: 4px;
      }
      &_icon {
        width: 10px;
        height: 10px;
        background-color: green;
        border-radius: 50%;
        margin-left: -3px;
        margin-right: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        &_con {
          width: 4px;
          height: 4px;
          border-radius: 2px;
          background-color: #fff;
        }
      }
    }
  }
  .abstract {
    .el-form {
      display: flex;
      flex-wrap: wrap;
      width: 90%;
      margin: auto;
      justify-content: space-between;
      :deep(.common) {
        .el-form-item__label::after {
          content: '*';
          color: red;
          margin-left: 4px;
        }
      }
      .document,
      .phoneNumber1,
      .phoneNumber2 {
        :deep(.el-form-item__content) {
          flex-wrap: nowrap;
          align-items: flex-start;
        }
      }
    }
    .general,
    .address,
    .contact {
      width: 100%;
    }
    .general_title,
    .address_title,
    .contact_title {
      display: flex;
      align-items: center;
      &::before {
        content: '';
        display: block;
        width: 4px;
        height: 19px;
        background-color: #419b62;
        margin-right: 10px;
      }
    }
    .general_content,
    .address_content,
    .contact_content {
      display: flex;
      flex-wrap: wrap;
      .el-form-item {
        flex: 0 1 28%;
      }
      .csc {
        flex: auto;
        .el-select {
          flex: 0 1 17%;
          margin-right: 10px;
        }
      }
    }
    .btn {
      width: 100%;
      display: flex;
      justify-content: center;
    }
  }
  .historicalData {
    .el-form {
      display: flex;
      flex-wrap: wrap;
      width: 90%;
      margin: auto;
      .btn {
        margin-left: 10px;
      }
      :deep(.table_header) {
        background-color: gray !important;
      }
    }
  }
  .list_pagination {
    width: 100%;
    .el-pagination {
      width: 100%;
      justify-content: center;
    }
  }
}
</style>
